package algorithm.swordoff;

import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * 从上到下打印二叉树II
 * BFS使用队列
 */

public class SQ32_2 {

    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> ans = new LinkedList<>();
        if (root == null) return ans;

        Queue<TreeNode> queue = new LinkedList<TreeNode>() {{add(root);}};
        while (!queue.isEmpty()) {
            List<Integer> tmp = new LinkedList<>();
            int size = queue.size();
            // 基于队列实现的层先法,队列中必定是一层一层完整且顺序地加入的
            for (int i = 0; i < size; i++) {
                TreeNode poll = queue.poll();
                tmp.add(poll.val);
                if (poll.left != null) queue.add(poll.left);
                if (poll.right != null) queue.add(poll.right);
            }
            ans.add(tmp);
        }
        return ans;

    }

}
